/* eslint-disable */
import { getQueryString,trimText,doCalculation,doPost,sendSbList } from './tool.js'
import { insertMoment } from '../../lib/utils.js';
import { handleQysds } from './qysds.js';

function nextTick(findObj,tick){
  function doIt(){
    var obj=findObj()
    if(!obj){
      setTimeout(()=>{
        nextTick(findObj);
      },200);
    }
  }
  if(tick){
    setTimeout(doIt,tick);
  }else{
    doIt();
  }
}

let currentZeroInfo;

const pages={
  "index":"https://etax.shandong.chinatax.gov.cn/EnterpriseDzswjMainAction.do?activity=pre_main",
  "step1":"https://etax.shandong.chinatax.gov.cn/EnterpriseDzswjMainAction.do?activity=dzswj_ts_ywlx",
  "step2":"/shenbao/dsIndex.action",
  "step3":"/portal/include_sb.do?app_bh=030121310",
  "step50": 'etax.shandong.chinatax.gov.cn/EnterpriseDzswjMainAction.do?activity=dzswj_ywlx', // 企业所得税
}

const isPage=(name)=>{
  return window.location.href.includes(pages[name])
}

const startZeroReport = async (data) => {
  if ('https://etax.shandong.chinatax.gov.cn/enterprise/dzswjlogin/dzswj_login.jsp?type=main'===window.location.href) {
    handleLogin(data.data.currentZeroInfo);
  }
  if('https://etax.shandong.chinatax.gov.cn/'===window.location.href){
    window.location.href='https://etax.shandong.chinatax.gov.cn/enterprise/dzswjlogin/dzswj_login.jsp?type=main';
  }
  currentZeroInfo=data.data.currentZeroInfo;
};

const handleLogin=(info)=>{
  window.sessionStorage.setItem('isZero',true);
  nextTick(()=>{
    let username=$("#userId"),password=$("#password");
    console.log(username);
    if(username.length && password.length){
      username.focus();
      username.val(info.nationalTaxNo);
      username.blur();
      password.focus();
      password.val(info.nationalTaxPass);
      password.blur();
      return true
    }
  },500)
}

const handleIndex=()=>{
  insertMoment();
  nextTick(()=>{
    let lis = $("#sbztdiv > table > tbody > tr");
    if(lis.length) {
      let qysds = Array.from(lis).find(item => $(item).find('td:nth-child(1)').text() === '企业所得税季度A类申报');
      let fjs = Array.from(lis).find(item => $(item).find('td:nth-child(1)').text() === '城建税及教育费附加');
      let zzs = Array.from(lis).find(item => $(item).find('td:nth-child(1)').text() === '增值税申报');
      let cwbb = Array.from(lis).find(item => $(item).find('td:nth-child(1)').text() === '财务报表');
      if(cwbb && $(cwbb).find('#sbzt').text().includes('未申报')) {
        
      } else if(qysds && $(qysds).find('#sbzt').text().includes('未申报')) {
        // $(qysds).find('td:nth-child(4) a').click();
      } else if(fjs && $(fjs).find('#sbzt').text().includes('未申报')) {

      } else if(zzs && $(zzs).find('#sbzt').text().includes('未申报')) {

      } else {
        console.log('申报成功');
      }
      return true;
    }
    
    // let isZeroEnd=window.sessionStorage.getItem("isZeroEnd");
    // if(isZeroEnd=="1"){
    //   getStatus();
    // }else{
    //   var btn=$("#ment_ctn_tsyw [data-index='2'] a");
    //   console.log(btn.html());
    //   if(btn.length && btn.html()==="增值税一般纳税人申报表一表集成"){
    //   btn.click();
    //   return true;
    //   }
    // }

    // return true;

  },1000)
}

const getStatus=()=>{
  nextTick(()=>{
    let arr=[false,false,false,false];
    $("#divmain table:eq(0) tr").each((idx,item)=>{
      if(idx>0){
        let label=$('td:eq(0)',item).html(),text=$('td:eq(2) a',item).html(),times=window.sessionStorage.getItem("zeroTimes");
        console.log(text,text==="申报成功");
        if(label==="财务报表(年度)"){
          arr[2]=text.trim()==="申报成功";
        }else if(label==="城建税及教育费附加"){
          arr[1]=text.trim()==="申报成功";
        }else if(label==="企业所得税年度申报"){
          arr[3]=text.trim()==="申报成功";
        }else if(label==="增值税申报"){
          arr[0]=text.trim()==="申报成功";
        }
        //如果两个都申报成功或者已经尝试了20次
        if((arr[0] && arr[1]) || parseInt(times)>20){
          sendSbList(currentZeroInfo,arr);
          setTimeout(()=>{
            window.sessionStorage.clear();
            tcxt();
          },2000);
        }else{
          setTimeout(()=>{
            times=times?parseInt(times)+1:1;
            window.sessionStorage.setItem("zeroTimes",times);
            window.location.reload();
          },5000);
        }
      }
    })
    return true;
  })
}

const handleStep1=()=>{
  saveTable2();
}

const saveTable2=()=>{
  nextTick(()=>{
    var btn=$("#main-left .panel-content:eq(1) a:eq(1)");
    console.log(btn);
    if(btn.length && btn.html()==="增值税纳税申报表附列资料（表二）"){
      btn.click();
      nextTick(()=>{
        if($("#ifr_tab_211").length){
          let win=$("#ifr_tab_211")[0].contentWindow;
          win.doCalculation=doCalculation.bind(win);
          win.doPost=doPost.bind(win);
          win.loadxx();
          nextTick(()=>{
            if(win.$("#savee").length){
              win.save();
              setTimeout(()=>{
                saveTable1();
              },1000)
              return true;
            }
          },200);
          return true;
        }
      },2000);
      return true;
    }
  })
}

const saveTable1=()=>{
  nextTick(()=>{
    var btn=$("#main-left .panel-content:eq(1) a:eq(3)");
    console.log(btn);
    if(btn.length && btn.html()==="增值税纳税申报表附列资料（表一）"){
      btn.click();
      nextTick(()=>{
        if($("#ifr_tab_213").length){
          let win=$("#ifr_tab_213")[0].contentWindow;
          win.doCalculation=doCalculation.bind(win);
          win.doPost=doPost.bind(win);
          win.loadxx();
          nextTick(()=>{
            if(win.$("#savee").length){
              win.save();
              setTimeout(()=>{
                saveTable4();
              },1000);
              return true;
            }
          },200);
          return true;
        }
      },1000);
      return true;
    }
  })
}

const saveTable4=()=>{
  nextTick(()=>{
    var btn=$("#main-left .panel-content:eq(1) a:eq(4)");
    console.log(btn);
    if(btn.length && btn.html()==="增值税纳税申报表附列资料（表四）"){
      btn.click();
      nextTick(()=>{
        if($("#ifr_tab_214").length){
          let win=$("#ifr_tab_214")[0].contentWindow;
          win.doCalculation=doCalculation.bind(win);
          win.doPost=doPost.bind(win);
          win.loadxx();
          nextTick(()=>{
            if(win.document.getElementById("savee")){
              win.save();
              setTimeout(()=>{
                saveTable5();
              },1000);
              return true;
            }
          },200);
          return true;
        }
      },1000);
      return true;
    }
  })
}

const saveTable5=()=>{
  nextTick(()=>{
    var btn=$("#main-left .panel-content:eq(1) a:eq(5)");
    console.log(btn);
    if(btn.length && btn.html()==="增值税纳税申报表（适用于增值税一般纳税人）"){
      btn.click();
      nextTick(()=>{
        if($("#ifr_tab_215").length){
          let win=$("#ifr_tab_215")[0].contentWindow;
          win.trimText=trimText.bind(win);
          win.doCalculation=doCalculation.bind(win);
          win.doPost=doPost.bind(win);
          //win.loadxx();
          win.trimText("C22_3");
          setTimeout(()=>{
            win.save();
            setTimeout(()=>{
              submitSb();
            },1000);
          },200);
          return true;
        }
      },1000);
      return true;
    }
  })
}

const submitSb=()=>{
  nextTick(()=>{
    var btn=$("#main-left .panel-content:eq(1) a:eq(12)");
    console.log(btn);
    if(btn.length && btn.html()==="增值税确认申报"){
      btn.click();
      nextTick(()=>{
        if($("#ifr_tab_222").length){
          let win=$("#ifr_tab_222")[0].contentWindow;
          setTimeout(()=>{
            win.upLoad();
            setTimeout(()=>{
              sbExtend();
            },1000)
          },200);
          return true;
        }
      },1000);
      return true;
    }
  })
}

const sbExtend=()=>{
  nextTick(()=>{
    var btn=$("#main-left .panel-content:eq(1) a:eq(14)");
    console.log(btn);
    if(btn.length && btn.html()==="城建税、教育费附加、地方教育附加税(费)申报"){
      btn.click();
      nextTick(()=>{
        if($("#ifr_tab_224").length){
          let win=$("#ifr_tab_224")[0].contentWindow;
          setTimeout(()=>{
            let str=win.$("saveButton").getAttribute("disabled");
            if(str!==""){
              win.save();
              setTimeout(()=>{
                endSb();
              },1000)
            }else{
              endSb();
            }
          },200);
          return true;
        }
      },1000);
      return true;
    }
  })
}

const endSb=()=>{
  window.sessionStorage.setItem("isZeroEnd",1);
  _app.back();
}



const checkZeroReport = ()=>{
  let isZero=window.sessionStorage.getItem("isZero");
  if(isZero!="true"){
    return;
  }
  nextTick(() => {
    if(currentZeroInfo) {
      if(isPage('index')){
        handleIndex();
      }else if(isPage('step1')){
        handleStep1();
      } else if(isPage('step50')) { // 企业所得税
        handleQysds();
      }
      return true;
    }
  })
  
}


export {
  startZeroReport,
  checkZeroReport
};
